package com.bootsecurity.security.config;

import com.bootsecurity.security.service.UserService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: liubin
 * Date: 2018-01-03
 * Time: 下午 5:51
 * @author 001030
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    UserDetailsService customUserService() {
        return new UserService();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //user Details Service验证
        auth.userDetailsService(customUserService())
            //自定义密码验证，不加会出现java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id “null” 异常
            .passwordEncoder(new MyPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //任何请求,登录后可以访问
                .anyRequest().authenticated().and()
                //登录页面用户任意访问
                .formLogin().loginPage("/login").failureUrl("/login?error").permitAll().and()
                //注销行为任意访问
                .logout().permitAll().and()
                //session管理
                .sessionManagement()
                .maximumSessions(1)
                .expiredUrl("/login?expired");
    }

    /**
     * 解决静态资源的拦截问题
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        //解决静态资源被拦截的问题
        web.ignoring().antMatchers("/css/**");
    }

}
